package com.erdos.common.web.tag;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.erdos.upc.core.UpcUser;
import com.erdos.upc.core.UpcUtil;
import com.erdos.upc.entity.Privilege;


public class PrivilegeTag extends BodyTagSupport{
	/**
	 * 
	 */
	private static final long serialVersionUID = 9077285455381522364L;
	private final static Log logger = LogFactory.getLog(PrivilegeTag.class);
	//处理开发模式不校验按钮权限；
	private static final Boolean dev = false;
	/**
	 * 权限codes
	 */
	private String privilegeCodes;

	public void setPrivilegeCodes(String privilegeCodes) {
		this.privilegeCodes = privilegeCodes;
	}

	/**
	 * 标签核心方法
	 */
	public int doStartTag() throws JspException {
	    //处理开发模式；
	       if (dev){
		 return EVAL_BODY_INCLUDE;
	       }
		logger.debug("start privilege tag");
		logger.debug("privilegeCodes:" + privilegeCodes);
		// 获取session
//		HttpSession session = (HttpSession) pageContext.getSession();
//		UpcUser upcUser = (UpcUser) session.getAttribute("upcUser");
		UpcUser upcUser=UpcUtil.getUpcUser((HttpServletRequest) pageContext.getRequest());
		Set<String> userPriCodes = this.getUserPrivilegeCode(upcUser);
		if (StringUtils.isNotEmpty(privilegeCodes)) {
			String[] pcodes = privilegeCodes.split(",");
			for (String pcode : pcodes) {
				if (userPriCodes.contains(pcode)) {
					return EVAL_BODY_INCLUDE;
				}
			}
			return SKIP_BODY;
		} else {
			return EVAL_BODY_INCLUDE;
		}
	}

	/**
	 * 获取用户的权限集合
	 * @param upcUser
	 * @return
	 */
	private Set<String> getUserPrivilegeCode(UpcUser upcUser) {
		Set<String> userPriCodes = new HashSet<String>();
		if (upcUser != null && upcUser.getPrivileges() != null) {
			for (Privilege p : upcUser.getPrivileges()) {
				userPriCodes.add(p.getCode());
			}
		}
		return userPriCodes;
	}

}
